package cn.com.netedge.iot.protocol.utils;

import com.alibaba.fastjson2.JSON;
import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.constants.MqConstants;
import cn.com.netedge.iot.common.dataobject.DeviceRunningInfo;
import cn.com.netedge.iot.common.dataobject.SendFrame;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 发送报文
 */
@Component
public class SendMessageUtil {
    private static Logger logger = LoggerFactory.getLogger(SendMessageUtil.class);

    public void sendDownMessage(String deviceNumber, int deviceType,  byte[] data) {
        SendFrame frame = buildBaseFrame(deviceNumber, deviceType, data);
        sendDownMessage(frame);
    }

    private SendFrame buildBaseFrame(String deviceNumber, int deviceType, byte[] data) {
        SendFrame frame = new SendFrame();
        frame.setDeviceNumber(deviceNumber);
        frame.setDeviceType(deviceType);
        frame.setData(data);
        return frame;
    }

    private void sendDownMessage(SendFrame frame) {
        String deviceNumber = frame.getDeviceNumber();
        int deviceType = frame.getDeviceType();
        String machineName = getMachineName(deviceNumber, deviceType);
        if (StringUtil.isEmpty(machineName)) {
            logger.debug("deviceNumber:{}  deviceType:{} is empty.", deviceNumber, deviceType);
            return;
        }
        String queueName = MqConstants.QUEUE_DOWN_MESSAGE + "." + machineName;

        JmsMsgUtil.sendMessage(queueName, JSON.toJSONString(frame));
    }

    private String getMachineName(String deviceNumber, int deviceType) {
        if (StringUtil.isEmpty(deviceNumber) || deviceType < 0) {
            logger.debug("deviceNumber or deviceType is empty.");
            return null;
        }
        String key = CacheKeyConstants.KEY_DEVICE_RUNNING + deviceNumber + "_" + deviceType;
        String info = RedisUtil.get(key);
        if (StringUtil.isEmpty(info)) {
            logger.debug("key:{} 's value is empty.");
            return null;
        }
        DeviceRunningInfo deviceRunningInfo = JSON.parseObject(info, DeviceRunningInfo.class);
        if (deviceRunningInfo == null) {
            logger.debug("{} convert deviceRunningInfo failed.", info);
            return null;
        }
        logger.debug("get machine name, deviceRunningInfo:{}", info);
        return deviceRunningInfo.getMachineName();
    }

}
